import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { CouponUserEntity } from '../entity/user';
import { CouponInfoEntity } from '../entity/info';

/**
 * 用户优惠券
 */
@Provide()
export class CouponUserService extends BaseService {
  @InjectEntityModel(CouponUserEntity)
  couponUserEntity: Repository<CouponUserEntity>;

  @InjectEntityModel(CouponInfoEntity)
  couponInfoEntity: Repository<CouponInfoEntity>;

  /**
   * 获取用户优惠券列表
   * @param userId 用户ID
   */
  async userCanUseCouponList(userId: number) {
    // 获取用户的优惠券关联记录
    const userCoupons = await this.couponUserEntity.find({
      where: { 
        userId: userId,
        status: 0,
       }
    });

    // 如果没有优惠券，直接返回空数组
    if (!userCoupons || userCoupons.length === 0) {
      return [];
    }

    // 获取所有相关的优惠券详细信息
    const couponIds = userCoupons.map(uc => uc.couponId);
    const coupons = await this.couponInfoEntity.find({
      where: { id: In(couponIds) }
    });

    // 合并优惠券信息和使用状态
    return userCoupons.map(userCoupon => {
      const couponInfo = coupons.find(c => c.id === userCoupon.couponId);
      return {
        'userCouponId': userCoupon.id,
        ...couponInfo,
      };
    });
  }
}
